const _ = require('./underscore');
const utils = require('./util');
const wgSign = require('./wgSign');
const _throttle = {
	/**
	 * 触发401登录限流(可能导致多次打开登录页面)
	 */
	loginOpening: false,
	login: _.throttle(
		() => {
			let pages = getCurrentPages(),
				p = pages[pages.length - 1];
			console.log('进入登录限流函数', _throttle.loginOpening, p);

			// 多次打开登录页面导致shareUserId清空
			let inviteId = ''
			if (p.options && p.options.userId) {
				inviteId = p.options.userId
			}


			if (!_throttle.loginOpening && p.route !== '/pages/mine/mine') {
				//退出登录
				utils.signOut();
				//打开登录页面
				_throttle.loginOpening = true;

				utils.checkLoginState({
					routeUri: 3,
					routeLogin: 3,
					callback() {
						_throttle.loginOpening = false;
					}
				});
			}

			// 退出登录以后再存一次inviteId
			if (inviteId) {
				wx.setStorageSync('inviteId', inviteId)
			}

		}, 3000, {
			'trailing': false
		})
};

const request = function (method, url, data,isXinkai) {
	let app = getApp() || this, //使用this是因为app.js中的调用还未生成app实例，getApp()是undefined
		globalData = app.globalData,
		// baseUrl1 = app.globalData.isDev ? 'http://47.114.5.153:8082/v1/api' : 'https://tntbeauty.cn/index.php/v1/api',
		baseUrl1 = app.globalData.isDev ? 'http://47.114.5.153:8082/v1/api' : 'https://tntbeauty.cn/index.php/v1/api',
		// baseUrl2 = app.globalData.isDev ? 'http://47.114.5.153:8082/v1/api' : 'https://xhbehappy.cn/v1/api',
		// baseUrl=isXinkai?baseUrl1:baseUrl2,
		baseUrl=baseUrl1,
		wg = wgSign.sign(method, url, data); //网关需要的字段

	return new Promise((resolve, reject) => {
		let isFullUrl = url.match(/^http[s]?:\/\//),
			reqUrl = isFullUrl ? url : baseUrl + url,
			header = app.getHeader();

		console.debug(reqUrl);
		let token = wx.getStorageSync('token')
		wx.request({
			url: reqUrl,
			data: data || {},
			method: method,
			header: {
				"appid": wg.appid,
				"token": token || '',
				"timestamp": wg.timestamp,
				"nonce": wg.nonce,
				"sigture": wg.sigture,
				...header,
			},
			success(res) {
				let statusCode = res.statusCode, //接口返回状态码
					isSuccess = res.data.success || res.data.Success; //新网关返回状态(新增大驼峰是为兼容运管接口)
				console.log(statusCode, 'statusCode', res, '接口成功')
				//接口返回状态正常 && isSuccess
				if (statusCode === 200 ) {
					if(res.data.ErrCode === '40004' || res.data.ErrCode === '40005' || res.data.ErrCode === '40008'){
						_throttle.login();
					}else{
						resolve(res);
					}
				}
				//请求状态为401未授权
				else if (statusCode === 401) {
					console.error(url, res);
					//限流打开登录
					// _throttle.login();
				} 
				
				//接口返回状态为其他异常
				else {
					console.error(url, res);
					reject(res);
				}
			},
			fail(res) {
				console.error(url, res);
				res.failReason = '小程序发起请求失败';
				reject(res);
			},
		})
	})
};

module.exports = {
	request,
};